package com.lh.auth.controller;

import com.lh.auth.conf.JwtProperties;
import com.lh.auth.pojo.UserInfo;
import com.lh.auth.service.IAuthService;
import com.lh.auth.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuhe
 * @date 2020/07/07
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    private final IAuthService iAuthService;
    private final JwtProperties jwtProperties;

    public AuthController(IAuthService iAuthService, JwtProperties jwtProperties) {
        this.iAuthService = iAuthService;
        this.jwtProperties = jwtProperties;
    }

    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response) {
        String authentication = this.iAuthService.authentication(username, password);
        if (StringUtils.isBlank(authentication)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), authentication, this.jwtProperties.getCookieMaxAge());
        return ResponseEntity.ok().build();
    }

    // 此处也可以在参数中使用@CookieValue("LY_TOKEN")String token，获取token,后边代码就不用从request中获取了
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = this.iAuthService.verifyUserAndUpdateCookie(request, response);
        if (null == userInfo) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok(userInfo);
    }
}
